<!-- 分类字典 -->
<template>
  <div class="app-container">
    <div class="container" :style="{ minHeight: minHeight }">
      <!-- 左边的用户-->
      <div class="column flex-item-1">
        <div class="chatBg chatLeft" :style="{ minHeight: minHeight }">
          <el-tabs v-model="leftTabActive" @tab-change="handleTabClick">
            <!-- 在线用户-->
            <el-tab-pane label="在线用户" name="first">
              <div
                v-for="item in users" :key="item.uid" :title="item.last_message" style="cursor:pointer"
                class="onlineUsers hasLastMsg"
                :class="{ cur: item.uid == currentGuest }"
                @click="talkTo(item.uid, item.username)"
              >
                <!--  消息提醒的红点  -->
                <el-badge
                  value="new"
                  :hidden="item.hiddenNewMessage"
                  class="left-block"
                >
                  <el-avatar :size="40" :src="item.avator"></el-avatar>
                </el-badge>

                <div class="right-container">
                  <div class="right-top">{{ item.username }}</div>
                  <!--  最新的一条消息 -->
                  <div class="lastNewMsg">
                    {{ item.last_message.length > 8 ? item.last_message.substring(0, 8) + '...' : item.last_message }}
                  </div>
                </div>
              </div>
            </el-tab-pane>
            <!-- 已接访客-->
            <el-tab-pane label="已接访客" name="second">
              <div v-for="item in visitors" :key="item.uid" class="">
                <div
                  style="cursor:pointer" class="onlineUsers" :class="{'cur': item.visitor_id==currentGuest }"
                  @click="talkTo(item.visitor_id, item.name)"
                >

                  <el-avatar
                    :class="{ imgGray: item.status == 0 }"
                    :size="40"
                    :src="item.avator"
                  ></el-avatar>

                  <div
                    style="height: 40px; overflow: hidden;font-size:12px"
                    :span="16"
                    :class="{ imgGray: item.status == 0 }"
                  >
                    {{ item.name }}
                  </div>
                </div>
              </div>
              <el-pagination
                v-show="visitorCount > visitorPageSize"
                background
                layout="prev,pager, next"
                :page-size="visitorPageSize"
                :total="visitorCount"
                @current-change="getVisitorPage"
              >
              </el-pagination>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <!-- 中间的聊天窗口 -->
      <div class="column flex-item-2"  ref="middleColumnRef">
        <div class="row">
          <!-- 顶部提醒     -->
          <el-alert
            :closable="false"
            :type="chatTitleType"
            show-icon
            :title="chatTitle + chatInputing"
          >
          </el-alert>
          <!-- 加载过去聊天记录   -->
          <div class="kefuFuncBtns" v-if="visitor.visitor_id" style="display: none">
            <el-button v-on:click="getMesssagesByVisitorId(visitor.visitor_id,true)" size="small" type="success" plain
                       icon="el-icon-user">加载全部
            </el-button>
            <el-button v-on:click="transKefu" size="small" type="success" plain icon="el-icon-position">转接</el-button>
            <el-button v-on:click="closeVisitor(visitor.visitor_id)" size="small" type="success" plain
                       icon="el-icon-close">结束
            </el-button>
          </div>
          <!-- 聊天记录窗口          -->
          <div ref="chatBoxDiv" class="chatBox" style="height: 63vh">
            <div style="text-align: center;" @click="getHistoryMessage" v-show="showLoadMore">
              <a href="javascript:;" class="chatNoticeContent" style="color: #07a9fe;">点击加载更多记录</a>
            </div>
            <div v-for="v in msgList">
              <div class="chatTime">{{ v.time }}</div>
              <div v-if="v.is_kefu===false" class="chatRow">
                <!--  客户头像    -->
                <el-avatar
                  v-if="v.is_kefu === false"
                  class="chatRowAvator"
                  :size="48"
                  :src="v.avator"
                ></el-avatar>
                <div class="chatMsgContent">
                  <div class="chatUser">{{ v.name }}</div>
                  <div class="chatContent" v-html="v.content" @click="showBigImg($event)"></div>
                </div>
              </div>
              <div v-if="v.is_kefu" class="chatRow chatRowMe">
                <div class="chatMsgContent">
                  <div class="chatUser">{{ v.name }}</div>
                  <div class="chatContent" v-html="v.content" @click="showBigImg($event)"></div>
                </div>
                <!-- 图片预览  -->
                <el-image-viewer v-if="imgViewerVisible" @close="closeImgViewer"
                                 :url-list="[currentImgViewerUrl]"></el-image-viewer>
                <!--  客服头像  -->
                <el-avatar
                  v-if="v.is_kefu === true"
                  class="chatRowAvator"
                  :size="48"
                  :src="v.avator"
                ></el-avatar>
              </div>
            </div>
          </div>
        </div>
        <div class="row">
          <div v-show="showFaceIcon" class="kefuFaceBox" :style="floatingDivStyle">
            <ul class="faceBoxList">
              <li
                v-for="(v, i) in face"
                class="faceIcon"
                :title="v.name"
                @click="faceIconClick(i)"
              >
                <img alt :src="v.img"/>
              </li>
            </ul>
          </div>
          <!-- 打字窗口    -->
          <div class="kefuFuncBox" :style="{ height: msgHeight }">
            <div class="iconBtnsBox">
              <el-tooltip content="发送表情" placement="top-start">
                <div
                  class="iconBtn iconfont icon-xiaolian" style="font-size: 24px;"
                  @click.stop="
                    showFaceIcon == true
                      ? (showFaceIcon = false)
                      : (showFaceIcon = true)
                  "
                ></div>
              </el-tooltip>
              <el-tooltip content="上传图片" placement="top">
                <div
                  class="iconBtn iconfont icon-jietu" style="font-size: 24px;"
                  @click="openImgInput">
                  <!-- 隐藏的文件输入 -->
                  <input
                    ref="imgInput"
                    v-if="showImgInput"
                    type="file"
                    style="display: none"
                    accept="image/*"
                    @change="handleImgUpload"
                  />
                </div>
              </el-tooltip>
              <el-tooltip content="上传附件" placement="top-end">
                <div id="uploadFile" @click="openFileInput"
                     style="font-size: 26px;">
                  <i-ep-folder/>
                  <!-- 隐藏的文件输入 -->
                  <input
                    ref="fileInput"
                    v-if="showFileInput"
                    type="file"
                    style="display: none"
                    accept="file/*"
                    @change="handleFileUpload"
                  />
                </div>
              </el-tooltip>
            </div>
            <div class="clear"></div>

            <el-input
              v-model="messageContent" type="textarea" :autosize="{ minRows: 9, maxRows: 9}" class="chatArea"
              placeholder="请输入内容"
              @mouseup="selectText"
              @keyup.enter.native="chatToUser"
            ></el-input>
            <el-button
              class="kefuSendBtn"
              :disabled="sendDisabled"
              size="small"
              type="primary"
              @click="chatToUser"
            >
              发送
            </el-button>
          </div>
        </div>
      </div>
      <!-- 右边的访客信息 -->
      <div class="column flex-item-3">
        <!-- 访客信息与黑名单      -->
        <div class="row">
          <div class="chatBg chatRight" :style="{ height: visitorHeight }">
            <el-tabs v-model="rightTabActive" @tab-change="rightTabClick">
              <!--  访客信息 -->
              <el-tab-pane label="访客信息" name="visitorInfo">
                <el-menu v-show="visitor.visitor_id" bg-color="yellow" class="visitorInfo">
                  <el-tooltip content="点击加入黑名单" placement="left">
                    <el-menu-item
                      title="点击加入黑名单" style="padding-left: 2px;"
                      @click="addIpblack(visitor.source_ip)"
                    >
                      <template #title>
                        <span>IP地址：{{ visitor.source_ip }}</span>
                      </template>
                    </el-menu-item>
                  </el-tooltip>
                  <el-menu-item style="padding-left: 2px; ">
                    <template #title>
                      <span>城市：{{ visitor.city }}</span>
                    </template>
                  </el-menu-item>
                  <el-menu-item style="padding-left: 2px; ">
                    <template #title>
                      <span>首次访问：{{ visitor.created_at }}</span>
                    </template>
                  </el-menu-item>
                  <el-menu-item style="padding-left: 2px; ">
                    <template #title>
                      <span>最后访问：{{ visitor.updated_at }}</span>
                    </template>
                  </el-menu-item>
                  <el-tooltip :content="visitor.refer" placement="left">
                    <el-menu-item style="padding-left: 2px;">
                      <template #title>
                        <span>来源标题：{{ visitor.refer }}</span>
                      </template>
                    </el-menu-item>
                  </el-tooltip>
                  <el-tooltip
                    v-for="v in visitorExtra"
                    :content="v.val"
                    placement="left"
                  >
                    <el-menu-item style="padding-left: 2px;">
                      <template #title>
                        <span style="max-width: 180px">{{ v.key }}：{{ v.val }}</span>
                      </template>
                    </el-menu-item>
                  </el-tooltip>
                </el-menu>
              </el-tab-pane>

              <!--  黑名单 -->
              <el-tab-pane label="黑名单" name="blackList">
                <el-row v-for="item in ipBlacks" :key="item.id" class="">
                  <el-tooltip content="点击删除黑名单" placement="left">
                    <div
                      style="cursor: pointer"
                      class="onlineUsers imgGray"
                      @click="delIpblack(item.ip)"
                    >
                      <ul>
                        <li>ip: {{ item.ip }}</li>
                        <li>添加时间: {{ item.createAt }}</li>
                      </ul>
                    </div>
                  </el-tooltip>
                </el-row>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
        <!--   快捷回复    -->
        <div class="row">
          <!--  快捷回复       -->
          <div class="replyBox" :style="{ height: replayHeight }">
            <div class="chatRightTitle">
              快捷回复
              <el-button link @click="replyGroupDialog = true">+添加分组</el-button>
            </div>
            <el-input
              v-model="replySearch" placeholder="选中文字自动搜索" class="replySearch"
              @keyup.enter="searchReply"
            >
              <template #append>
                <el-button icon="el-icon-search" @click="searchReply"></el-button>
              </template>
            </el-input>
            <div class="replyContent">
              <!-- 查询的快捷回复      -->
              <el-collapse
                v-show="replySearchList"
                v-model="replySearchListActive"
              >
                <el-collapse-item
                  v-for="reply in replySearchList" :key="reply.group_id" :title="reply.group_name"
                  :name="reply.group_id"
                >
                  <div
                    v-for="item in reply.items"
                    class="replyItem"
                    @click="messageContent = item.item_content"
                  >
                    {{ item.item_content }}
                    <el-button text @click="deleteReplyContent(item.item_id)">
                      删除
                    </el-button>
                  </div>
                  <el-button
                    text
                    @click="replyContentDialog=true;groupName=reply.group_name;groupId=reply.group_id"
                  >
                    +添加回复内容
                  </el-button>
                  <el-button @click="deleteReplyGroup(reply.group_id)"
                  >-删除组
                  </el-button
                  >
                </el-collapse-item>
              </el-collapse>
              <!-- 快捷回复展示  -->
              <el-collapse
                v-for="(reply, index) in replys"
                v-show="replySearchList.length === 0"
              >
                <el-collapse-item
                  :key="reply.group_id" :title="reply.group_name"
                  :name="reply.group_id"
                >
                  <div
                    v-for="item in reply.items"
                    class="replyItem"
                    @click="messageContent = item.item_content"
                  >
                    <el-popover placement="left" width="300" trigger="hover">
                      <template #reference>
                        <div slot="reference" class="replyItemTitle">
                          <i class="header-icon el-icon-document"></i>
                          {{ item.item_name }}
                        </div>
                      </template>
                      <div v-html="replaceContent(item.item_content)"/>
                    </el-popover>
                    <!--  编辑快捷回复消息  -->
                    <el-button
                      size="small"
                      type="primary"
                      @click="editReplyContent('no',item.item_id,item.item_name,item.item_content)"
                    >
                      编辑
                    </el-button>
                    <!--  删除快捷回复消息  -->
                    <el-button
                      size="small"
                      type="danger"
                      @click="deleteReplyContent(item.item_id)"
                    >删除
                    </el-button
                    >
                  </div>

                  <!--   针对组的操作 -->
                  <!--   添加回复内容 -->
                  <el-button
                    size="small"
                    type="primary"
                    @click="replyContentDialog=true;groupName=reply.group_name;groupId=reply.group_id"
                  >添加回复内容
                  </el-button>
                  <!--   删除组   -->
                  <el-popover
                    placement="top"
                    width="100"
                    :visible="visible[index]"
                  >
                    <p>确定删除吗？</p>
                    <div style="text-align: right">
                      <el-button
                        size="small"
                        text
                        @click="visible[index] = false"
                      >取消
                      </el-button
                      >
                      <el-button
                        type="primary"
                        size="small"
                        @click="deleteReplyGroup(reply.group_id)"
                      >
                        确定
                      </el-button>
                    </div>
                    <template #reference>
                      <el-button
                        size="small"
                        type="danger"
                        @click="visible[index] = true"
                      >删除组
                      </el-button
                      >
                    </template>
                  </el-popover>
                </el-collapse-item>
              </el-collapse>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!--  消息声音  -->
    <audio ref="chatMessageAudio">
      <source
        id="chatMessageAudioSource"
        src="@/assets/images/alert2.ogg"
        type="audio/mpeg"
      />
    </audio>
    <audio id="chatMessageSendAudio">
      <source
        id="chatMessageSendAudioSource"
        src="@/assets/images/sent.ogg"
        type="audio/mpeg"
      />
    </audio>

    <!--转接---------------------------------------------------------------------------------------------->
    <el-dialog v-model="transKefuDialog" title="转移客服" width="30%" top="0">
      <el-table :data="otherKefus" style="width: 100%">
        <el-table-column prop="nickname" label="客服"></el-table-column>
        <el-table-column prop="status" label="操作">
          <template #default="scope">
            <el-tag
              v-show="scope.row.status == 'offline'" disable-transitions
            >离线
            </el-tag>
            <el-button
              v-show="scope.row.status=='online'" type="primary"
              @click="transKefuVisitor(scope.row.name, visitor.visitor_id)"
            >转移
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="transKefuDialog = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--//转接-->
    <!--回复分组-->
    <el-dialog v-model="replyGroupDialog" title="添加分组" width="30%">
      <el-input v-model="groupName"></el-input>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addReplyGroup">保 存</el-button>
          <el-button type="primary" @click="replyGroupDialog = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--//回复分组-->
    <!--新增回复内容-->
    <el-dialog v-model="replyContentDialog" title="添加回复内容" width="30%">
      <el-input
        v-model="replyTitle"
        style="margin-bottom: 10px"
        placeholder="关键词"
      ></el-input>
      <el-input
        v-model="replyContent"
        placeholder="内容"
        type="textarea"
      ></el-input>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addReplyContent">保 存</el-button>
          <el-button type="primary" @click="replyContentDialog = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 编辑回复内容   -->
    <el-dialog
      v-model="editReplyContentDialog"
      title="编辑回复内容"
      width="30%"
    >
      <el-input
        v-model="replyTitle"
        style="margin-bottom: 10px"
        placeholder="关键词"
      ></el-input>
      <el-input
        v-model="replyContent"
        placeholder="内容"
        type="textarea"
      ></el-input>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="editReplyContent('yes')">保 存</el-button>
          <el-button type="primary" @click="editReplyContentDialog = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--//回复内容-->
  </div>
</template>
<script setup lang="js">
import {readMessage} from "@/api/message.js";

defineOptions({
  name: "Kefu",
  inherititems: false,
});
import request from "@/utils/request";
import {nextTick, ref} from "vue";
import UserAPI from "@/api/user";
import {TOKEN_KEY} from "@/enums/CacheEnum";
import {useSettingsStore} from "@/store/index";
import variables from "@/styles/variables.module.scss";
import {placeFace} from "@/assets/images/face/face.js"

//删除回复组弹窗打开
const visible = ref([]);
const chatTitleType = ref("info");
const fullscreenLoading = ref(true);
const leftTabActive = ref("first");
const rightTabActive = ref("visitorInfo");
const users = ref([]);
const usersMap = ref([]);
const socket = ref(null);
const socketClosed = ref(false);
const messageContent = ref("");
const currentGuest = ref("");
//消息列表
const msgList = ref([]);
const chatTitle = ref("暂时未处理咨询");
const chatInputing = ref("");
const kfConfig = reactive({
  id: "kf_1",
  name: "客服",
  avator: "",
  to_id: "",
});
let visitor = reactive({
  visitor_id: "",
  refer: "",
  client_ip: "",
  city: "",
  status: "",
  source_ip: "",
  created_at: "",
});
const server = ref(
  window.WS_RUL + "/ws_kefu?Authorization=" + localStorage.getItem(TOKEN_KEY),
);
const visitorExtra = ref([]);
const visitors = ref([]);
const visitorCount = ref(0);
const visitorPageSize = ref(10);
const face = ref([]);
const transKefuDialog = ref(false);
const otherKefus = ref([]);
const replyGroupDialog = ref(false);
const replyContentDialog = ref(false);
const editReplyContentDialog = ref(false);
const replySearch = ref("");
const replySearchList = ref([]);
const replySearchListActive = ref([]);
const groupName = ref("");
const groupId = ref("");
const replys = ref([]);
const replyId = ref("");
const replyContent = ref(""); //打字的内容
const replyTitle = ref("");
const ipBlacks = ref([]);
const sendDisabled = ref(false);
const showFaceIcon = ref(false);
const showLoadMore = ref(false);
const showImgInput = ref(true); //展示图片上传
const showFileInput = ref(true); //展示附件上传
//历史消息请求
const messages = reactive({
  page: 1,
  pagesize: 15,
  list: [],
});

const minHeight = computed(() => {
  if (useSettingsStore().tagsView) {
    return `calc(100vh - ${variables["navbar-height"]} - 5px - ${variables["tags-view-height"]})`;
  } else {
    return `calc(100vh - ${variables["navbar-height"]}) - 5px`;
  }
});
const chatHeight = computed(() => {
  if (useSettingsStore().tagsView) {
    return `calc(63vh - ${variables["tags-view-height"]})`;
  } else {
    return `calc(63vh)`;
  }
});
const msgHeight = computed(() => {
  if (useSettingsStore().tagsView) {
    return `calc(34vh - ${variables["navbar-height"]} - 5px - ${variables["tags-view-height"]})`;
  } else {
    return `calc(34vh - ${variables["navbar-height"]}) - 5px`;
  }
});
const visitorHeight = computed(() => {
  if (useSettingsStore().tagsView) {
    return `calc(50vh - ${variables["navbar-height"]} - 5px  - ${variables["tags-view-height"]})`;
  } else {
    return `calc(50vh - ${variables["navbar-height"]}) - 5px `;
  }
});

const replayHeight = computed(() => {
  if (useSettingsStore().tagsView) {
    return `calc(60vh - ${variables["navbar-height"]} - 5px  - ${variables["tags-view-height"]})`;
  } else {
    return `calc(60vh - ${variables["navbar-height"]}) - 5px `;
  }
});

const imgViewerVisible = ref(false);
const currentImgViewerUrl = ref('');

/**
 * 开启图片预览
 * @param e
 */
function showBigImg(e) {
  if (e.target.nodeName === 'IMG') {
    imgViewerVisible.value = true
    currentImgViewerUrl.value = e.target.src
  }
}

/**
 * 关闭图片预览
 */
function closeImgViewer() {
  imgViewerVisible.value = false
  currentImgViewerUrl.value = ''
}

initJquery();
getKefuInfo();
getOnlineVisitors();
getReplys();
getIpblacks();
//心跳
ping();

function sendKefuOnline(e) {
  console.log("onOpen", e);
  let mes = {};
  mes.type = "kfOnline";
  mes.data = kfConfig;
  socket.value.send(JSON.stringify(mes));
}

//心跳
function ping() {
  let mes = {};
  mes.type = "ping";
  mes.data = "";
  setInterval(function () {
    if (socket.value != null) {
      socket.value.send(JSON.stringify(mes));
    }
  }, 20000);
  setInterval(function () {
    console.log("getOnlineVisitors");
    getOnlineVisitors();
  }, 6000);
}

//初始化websocket
function initConn() {
  socket.value = new WebSocket(server.value); //创建Socket实例
  socket.value.onmessage = (e) => OnMessage(e);
  socket.value.onopen = (e) => OnOpen(e);
}

function OnOpen(e) {
  sendKefuOnline(e);
}

function OnMessage(e) {
  console.log(e);
  const redata = JSON.parse(e.data);
  switch (redata.type) {
    case "close":
      socket.value.close();
      ElMessageBox.confirm("客服ws链接关闭，登录状态退出", "通知", {
        confirmButtonText: "确定",
        type: "warning",
      }).then(() => {
        localStorage.removeItem("token");
        window.location.href = import.meta.env.VITE_APP_CONTEXT_PATH
      });
      break;
    case "inputing":
      handleInputing(redata.data);
      //sendKefuOnline();
      break;
    case "allUsers":
      handleOnlineUsers(redata.data);
      //sendKefuOnline();
      break;
    case "userOnline":
      addOnlineUser(redata.data);
      break;
    case "userOffline":
      removeOfflineUser(redata.data);
      //sendKefuOnline();
      break;
    case "notice":
      //发送通知
      window.parent.postMessage({
        name: redata.data.username,
        body: redata.data.content,
        icon: redata.data.avator,
      });
      alertSound();
      break;
  }

  if (redata.type === "message") {
    let msg = redata.data;
    let content = {};
    content.avator = msg.avator;
    content.name = msg.name;
    content.content = replaceContent(msg.content);
    content.is_kefu = msg.is_kefu === "yes" ? true : false;
    content.time = msg.time;
    if (msg.id === currentGuest.value) {
      msgList.value.push(content);
      //如果当前正在打开的这个聊天窗口本身就是这个客户的，那么客户发的消息直接置为已读
      readMessage(msg.id)
    }
    console.log("users",users)
    console.log("currentGuest.value",currentGuest.value)
    for (let i = 0; i < users.value.length; i++) {
      if (users.value[i].uid == msg.id) {
        users.value[i].last_message = msg.content;
        if (visitor.visitor_id != msg.id) {
          users.value[i].hiddenNewMessage = false;
        }
      }
    }
    scrollBottom();
    if (content.is_kefu) {
      return;
    }
    window.parent.postMessage({
      name: msg.name,
      body: msg.content,
      icon: msg.avator,
    });
    alertSound();
    chatInputing.value = "";
  }
}

//接手客户
function talkTo(guestId, name) {
  currentGuest.value = guestId;
  //发送给客户
  let mes = {};
  mes.type = "kfConnect";
  kfConfig.to_id = guestId;
  mes.data = kfConfig;
  socket.value.send(JSON.stringify(mes));
  //每次切换的时候都清空下输入的内容
  messageContent.value = ""
  //获取当前访客信息
  getVisitorInfo(guestId);
  //获取当前客户消息
  messages.page = 1;
  msgList.value = [];
  getHistoryMessage();
  //getMesssagesByVisitorId(guestId);
  for (let i = 0; i < users.value.length; i++) {
    if (users.value[i].uid == guestId) {
      users.value[i].hiddenNewMessage = true;
    }
  }
}

//发送给客户
function chatToUser() {
  messageContent.value = messageContent.value.trim("\r\n");
  messageContent.value = messageContent.value.replace("\n", "");
  messageContent.value = messageContent.value.replace("\r\n", "");
  if (
    messageContent.value == "" ||
    messageContent.value == "\r\n" ||
    currentGuest.value == ""
  ) {
    return;
  }
  if (sendDisabled.value) {
    return;
  }
  sendDisabled.value = true;
  let mes = {};
  mes.type = "kefu";
  mes.content = messageContent.value;
  mes.from_id = kfConfig.id;
  mes.to_id = currentGuest.value;
  mes.content = messageContent.value;
  request({
    url: "/2/message",
    method: "post",
    data: mes,
  }).then((res) => {
    sendDisabled.value = false;
    messageContent.value = "";
    sendSound();
  });
  // let content = {}
  // content.avator = this.kfConfig.avator;
  // content.name = this.kfConfig.name;
  // content.content = replaceContent(this.messageContent);
  // content.is_kefu = true;
  // content.time = '';
  // msgList.push(content);
  sendDisabled.value = false;
  scrollBottom();
}

//处理当前在线用户列表
function addOnlineUser(retData) {
  let flag = false;
  retData.status = 1;
  retData.name = retData.username;
  retData.hiddenNewMessage = true;
  for (let i = 0; i < users.value.length; i++) {
    if (users.value[i].uid == retData.uid) {
      flag = true;
    }
  }
  if (!flag) {
    users.value.unshift(retData);
  }
  for (let i = 0; i < visitors.value.length; i++) {
    if (visitors.value[i].visitor_id == retData.uid) {
      visitors.value[i].status = 1;
      break;
    }
  }
  if (visitor.visitor_id == retData.uid) {
    getVisitorInfo(retData.uid);
  }
}

//处理当前在线用户列表
function removeOfflineUser(retData) {
  for (let i = 0; i < users.value.length; i++) {
    if (users.value[i].uid == retData.uid) {
      users.value.splice(i, 1);
    }
  }
  let vid = retData.uid;
  for (let i = 0; i < visitors.value.length; i++) {
    if (visitors.value[i].visitor_id == vid) {
      visitors.value[i].status = 0;
      break;
    }
  }
}

//处理当前在线用户列表
function handleOnlineUsers(retData) {
  if (currentGuest.value === "") {
    chatTitle.value = "连接成功,等待处理中...";
  }
  usersMap.value = [];
  for (let i = 0; i < retData.length; i++) {
    usersMap.value[retData[i].uid] = retData[i].username;
    retData[i].last_message = "新访客";
  }
  if (users.value.length == 0) {
    users.value = retData;
  }
  for (let i = 0; i < visitors.value.length; i++) {
    let vid = visitors.value[i].visitor_id;
    if (typeof usersMap.value[vid] == "undefined") {
      visitors.value[i].status = 0;
    } else {
      visitors.value[i].status = 1;
    }
  }
}

//处理正在输入
function handleInputing(retData) {
  if (retData.from == visitor.visitor_id) {
    chatInputing.value = "|正在输入：" + retData.content + "...";
    if (retData.content == "") {
      chatInputing.value = "";
    }
  }
  for (let i = 0; i < users.value.length; i++) {
    if (users.value[i].uid == retData.from) {
      users.value[i].last_message = retData.content + "...";
    }
  }
}

//获取客服信息
function getKefuInfo() {
  UserAPI.getInfo().then((data) => {
    console.log("kefuinfo", data);
    kfConfig.id = data.userId;
    kfConfig.name = data.username;
    kfConfig.avator = data.avatar;
    initConn();
  });
}

//获取客服信息
function getOnlineVisitors() {
  request({
    url: "/visitors_kefu_online",
    method: "get",
  }).then((res) => {
    console.log("users", res);
    if (res != null) {
      users.value = res;
      // for (let i = 0; i < users.value.length; i++) {
      //   users.value[i].hiddenNewMessage = true;
      // }
    }
  });
}

//获取历史数据
function getHistoryMessage() {
  let params = {
    page: messages.page,
    pagesize: messages.pagesize,
    visitor_id: currentGuest.value,
  };
  request({
    url: "/api/v1/message/pageByVisitor",
    method: "get",
    params: params,
  }).then((res) => {
    let list = res.list;
    if (list.length >= messages.pagesize) {
      showLoadMore.value = true;
    } else {
      showLoadMore.value = false;
    }
    console.log("list", list);
    for (let i in list) {
      let item = list[i];
      //let content = {}
      if (item.mes_type === "kefu") {
        item.is_kefu = true;
        item.avator = item.kefu_avator;
        item.name = item.kefu_name;
      } else {
        item.is_kefu = false;
        item.avator = item.visitor_avator;
        item.name = item.visitor_name;
      }
      item.content = replaceContent(item.content);
      item.time = item.create_time;
      msgList.value.unshift(item);
    }
    if (messages.page === 1) {
      scrollBottom();
    }
    messages.page++;
  });
}

//获取信息列表
function getMesssagesByVisitorId(visitorId, isAll) {
  request({
    url: "/messages?visitorId=" + visitorId,
    method: "get",
    params: params,
  }).then((data) => {
    let i;
    if (data.code == 200 && data.result != null) {
      msgList.value = data.result;
      msgList.value = [];
      if (!isAll && msgList.value.length > 10) {
        i = msgList.value.length - 10;
      } else {
        i = 0;
      }
      for (; i < msgList.value.length; i++) {
        let visitorMes = msgList.value[i];
        let content = {};
        if (visitorMes["mes_type"] == "kefu") {
          content.is_kefu = true;
          content.avator = visitorMes["kefu_avator"];
          content.name = visitorMes["kefu_name"];
        } else {
          content.is_kefu = false;
          content.avator = visitorMes["visitor_avator"];
          content.name = visitorMes["visitor_name"];
        }
        content.content = replaceContent(visitorMes["content"]);
        content.time = visitorMes["time"];
        msgList.value.push(content);
        scrollBottom();
      }
    }
  });
}

//获取客服信息
function getVisitorInfo(vid) {
  request({
    url: "/visitor",
    method: "get",
    params: {visitorId: vid},
  }).then((data) => {
    console.log("getVistorInfo", data);
    visitor.visitor_id = data.visitor_id;
    visitor.refer = data.refer;
    visitor.source_ip = data.client_ip;
    visitor.city = data.city;
    visitor.created_at = data.created_at;
    visitor.updated_at = data.updated_at;
    visitor.status = data.status === 1 ? "在线" : "离线";
    // _this.visitor.refer=r.refer;
    // _this.visitor.city=r.city;
    // _this.visitor.client_ip=r.client_ip;
    // _this.visitor.source_ip=r.source_ip;

    //_this.visitor.visitor_id=r.visitor_id;
    chatTitle.value = "#" + data.id + "|" + data.name;
    chatTitleType.value = "success";
    visitorExtra.value = [];
    if (data.extra != "") {
      let extra = JSON.parse(decodeURIComponent(data.extra));
      if (typeof extra == "string") {
        extra = JSON.parse(extra);
      }
      for (const key in extra) {
        if (extra[key] === "") {
          extra[key] = "无";
        }
        if (key === "visitorAvatar" || key === "visitorName") continue;
        const temp = {key: key, val: extra[key]};
        visitorExtra.value.push(temp);
      }
    }
  });
}

//关闭访客
function closeVisitor(visitorId) {
  request({
    url: "/2/message_close",
    method: "get",
    params: {visitorId: vid},
  }).then((data) => {
  });
}

//处理tab切换
function handleTabClick(tab, event) {
  if (tab === "first") {
    getOnlineVisitors();
  }
  if (tab === "second") {
    getVisitorPage(1);
  }
  if (tab === "blackList") {
  }
}

//右侧tab切换
function rightTabClick(tab) {
  console.log("111", tab)
}

//获取访客分页
function getVisitorPage(page) {
  request({
    url: "/visitor/page",
    method: "get",
    params: {page: page, pagesize: visitorPageSize.value},
  }).then((data) => {
    if (data.list != null) {
      visitors.value = data.list;
      visitorCount.value = data.count;
      visitorPageSize.value = data.pagesize;
    }
  });
}

// 转义聊天内容中的特殊字符
function replaceContent(content, baseUrl) {
  if (typeof baseUrl == "undefined") {
    baseUrl = "";
  }
  const faces = face.value;
  content = (content || "")
    // 表情替换
    .replace(/face\[(.*?)\]/g, function (face) {
      // 转义表情
      const alt = face.replace(/^face/g, "");
      const found = faces.find((element) => element.name === alt);
      return (
        '<img alt="' + alt + '" title="' + alt + '" src="' + found.img + '">'
      );
    })
    //图片选择
    .replace(/img\[(.*?)\]/g, function (img) {
      // 转义图片
      const src = img.replace(/^img\[/g, "").replace(/\]/g, "");
      return (
        '<img src="' + baseUrl + src + '" style="max-width: 150px"/>'
      );
    })
    // 转义换行
    .replace(/\n/g, "<br>");
  //附件展示形式替换
  content = replaceAttachment(content);
  return content;
}

//替换聊天记录中的附件文本
function replaceAttachment(str) {
  return str.replace(/attachment\[(.*?)\]/g, function (result) {
    const mutiFiles = result.match(/attachment\[(.*?)\]/);
    console.log("mutiFiles",mutiFiles)
    if (mutiFiles.length < 2) {
      return result;
    }
    //return result;
    const info = JSON.parse(mutiFiles[1]);
    let imgSrc = "";
    switch (info.ext) {
      case ".mp3":
        imgSrc = "/static/images/ext/MP3.png";
        break;
      case ".zip":
        imgSrc = "/static/images/ext/ZIP.png";
        break;
      case ".txt":
        imgSrc = "/static/images/ext/TXT.png";
        break;
      case ".7z":
        imgSrc = "/static/images/ext/7z.png";
        break;
      case ".bpm":
        imgSrc = "/static/images/ext/BMP.png";
        break;
      case ".png":
        imgSrc = "/static/images/ext/PNG.png";
        break;
      case ".jpg":
        imgSrc = "/static/images/ext/JPG.png";
        break;
      case ".jpeg":
        imgSrc = "/static/images/ext/JPEG.png";
        break;
      case ".pdf":
        imgSrc = "/static/images/ext/PDF.png";
        break;
      case ".doc":
        imgSrc = "/static/images/ext/DOC.png";
        break;
      case ".docx":
        imgSrc = "/static/images/ext/DOCX.png";
        break;
      case ".rar":
        imgSrc = "/static/images/ext/RAR.png";
        break;
      case ".xlsx":
        imgSrc = "/static/images/ext/XLSX.png";
        break;
      case ".csv":
        imgSrc = "/static/images/ext/XLSX.png";
        break;
      default:
        imgSrc = "/static/images/ext/default.png";
        break;
    }
    const html =
      `<div onclick="window.open('` +
      info.path +
      `')" class="productCard">
                        <div><img src='` +
      imgSrc +
      `' style='width: 38px;height: 38px;' /></div>
                        <div class="productCardTitle">
                            <div class="productCardTitle">` +
      info.name +
      `</div>
                            <div style="font-size: 12px;color: #666">` +
      formatFileSize(info.size) +
      `</div>
                        </div>
                    </div>`;
    return html;
  });
}

/**
 * 格式化文件大小
 * @param fileSize
 * @returns {string}
 */
function formatFileSize(fileSize) {
  let temp;
  if (fileSize < 1024) {
    return fileSize + 'B';
  } else if (fileSize < (1024 * 1024)) {
    temp = fileSize / 1024;
    temp = temp.toFixed(2);
    return temp + 'KB';
  } else if (fileSize < (1024 * 1024 * 1024)) {
    temp = fileSize / (1024 * 1024);
    temp = temp.toFixed(2);
    return temp + 'MB';
  } else {
    temp = fileSize / (1024 * 1024 * 1024);
    temp = temp.toFixed(2);
    return temp + 'GB';
  }
}
const middleColumnRef = ref(null);
const floatingDivStyle = ref({});
// 监听窗口大小变化
const handleResize = () => {
  console.log("middleColumnWidth",middleColumnRef.value)
  if (middleColumnRef.value) {
    const middleColumnWidth = middleColumnRef.value.offsetWidth;
    const middleColumnLeft = middleColumnRef.value.offsetLeft;
    console.log("middleColumnWidth----",middleColumnWidth)
    // 更新浮动div的样式
    floatingDivStyle.value = {
      bottom: msgHeight.value,
      width: `${middleColumnWidth}px`
    };
  }
};
// 组件挂载时添加事件监听器
onMounted(() => {
  window.addEventListener('resize', handleResize);
  // 初始时也调用一次，以确保样式正确
  handleResize();
  document.body.addEventListener('paste', onPasteUpload);
});

// 组件卸载时移除事件监听器
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  document.body.removeEventListener('paste', onPasteUpload);
});

const chatBoxDiv = ref(null);

// 滚动到底部
function scrollBottom() {
  console.log("滚动到底部", chatBoxDiv.value.scrollHeight);
  nextTick(() => {
    if (chatBoxDiv.value) {
      console.log("滚动到底部-----", chatBoxDiv.value.scrollHeight);
      chatBoxDiv.value.scrollTop = chatBoxDiv.value.scrollHeight;
      console.log(
        "滚动到底部-----chatBoxDiv.value.scrollTop ",
        chatBoxDiv.value.scrollTop,
      );
    }
  });
}

//jquery
function initJquery() {
  //展示表情
  face.value = placeFace();
}

//表情点击事件
function faceIconClick(index) {
  showFaceIcon.value = false;
  messageContent.value += "face" + face.value[index].name;
}
//附件上传占位
const fileInput = ref(null);

// 点击div时，触发隐藏的input的点击事件
function openFileInput() {
  fileInput.value.click();
}
//图片上传占位
const imgInput = ref(null);

// 点击div时，触发隐藏的input的点击事件
function openImgInput() {
  imgInput.value.click();
}

// 处理文件选择后的逻辑
function handleImgUpload(event) {
  console.log("-------------------------", "上传图片", event)
  const file = event.target.files[0]; // 获取文件
  imgUpload(file)
}

// 处理文件选择后的逻辑
function handleFileUpload(event) {
  console.log("-------------------------", "上传图片", event)
  const file = event.target.files[0]; // 获取文件
  fileUpload(file)
}


/**
 * 上传图片
 * @param file
 */
function fileUpload(file) {
  if (file) {
    // 这里可以添加将文件上传到服务器的逻辑
    // 例如使用FormData和fetch API
    console.log("Selected file:", file);
    const formData = new FormData();
    formData.append("file", file); //传给后台的file的key值是可以自己定义的
    request({
      url: "uploadfile",
      method: "post",
      data: formData,
      headers: {
        "Content-Type": "multipart/form-data",
      },
    }).then((res) => {
      console.log("res",res)
      let data = JSON.stringify({
        name: res.name,
        ext: res.ext,
        size: res.size,
        path: "/" + res.path,
      });
      messageContent.value += "attachment[" + data + "]";
      chatToUser();
      //下面的showInput是为了重新渲染file，避免出现上传了一个图片再上传无法使用的情况
      showFileInput.value = false; // 隐藏input并准备重新渲染
      nextTick(() => {
        showFileInput.value = true; // 重新渲染input
      });
      scrollBottom();
    }).catch((err) => {
      console.log(err);
    })
  }
}


function filter(obj) {
  const imgType = ["image/jpeg", "image/png", "image/jpg", "image/gif"];
  const filetypes = imgType;
  const isnext = false;
  for (let i = 0; i < filetypes.length; i++) {
    if (filetypes[i] == obj.type) {
      return true;
    }
  }
  return false;
}

/**
 * 上传图片
 * @param file
 */
function imgUpload(file) {
  if (file) {
    // 这里可以添加将文件上传到服务器的逻辑
    // 例如使用FormData和fetch API
    console.log("Selected file:", file);
    const formData = new FormData();
    formData.append("imgfile", file); //传给后台的file的key值是可以自己定义的
    filter(file) &&
    request({
      url: "uploadimg",
      method: "post",
      data: formData,
      headers: {
        "Content-Type": "multipart/form-data",
      },
    }).then((data) => {
      messageContent.value += "img[/" + data.path + "]";
      chatToUser();
      //下面的showInput是为了重新渲染file，避免出现上传了一个图片再上传无法使用的情况
      showImgInput.value = false; // 隐藏input并准备重新渲染
      nextTick(() => {
        showImgInput.value = true; // 重新渲染input
      });
      scrollBottom();
    }).catch((err) => {
      console.log(err);
    })
  }
}

/**
 * 添加黑名单
 * @param ip
 */
function addIpblack(ip) {
  request({
    url: "/ipblack",
    method: "post",
    data: {ip: ip},
  }).then((data) => {
    ElMessage.success(data);
  });
}

//粘贴上传图片
function onPasteUpload(event) {
  console.log("clipboardData", event);
  let items = event.clipboardData && event.clipboardData.items;
  let file = null;
  if (items && items.length) {
    // 检索剪切板items
    for (let i = 0; i < items.length; i++) {
      if (items[i].type.indexOf("image") !== -1) {
        file = items[i].getAsFile();
      }
    }
  }
  if (!file) {
    return;
  }
  imgUpload(file)
}

// 聊天消息
const chatMessageAudio = ref(null)

//提示音
function alertSound() {
  const p = chatMessageAudio.value.play();
  p && p.then(function () {
  }).catch(function (e) {
  });
}
//发送的声音
function sendSound() {
  var b = document.getElementById("chatMessageSendAudio");
  var p = b.play();
  p && p.then(function () {
  }).catch(function (e) {
  });
}

//转移客服
function transKefu() {
  transKefuDialog.value = true;
  request({
    url: "/other_kefulist",
    method: "get",
  }).then((res) => {
    otherKefus.value = res;
  });
}

//转移访客客服
function transKefuVisitor(kefu, visitorId) {
  request({
    url: "/trans_kefu",
    method: "get",
    params: {kefu_id: kefu, visitor_id: visitorId},
  }).then((res) => {
    transKefuDialog.value = false;
  });
}

//保存回复分组
function addReplyGroup() {
  request({
    url: "/reply",
    method: "post",
    data: {group_name: groupName.value},
  }).then((res) => {
    replyGroupDialog.value = false;
    groupName.value = "";
    getReplys();
  });
}

//添加回复内容
function addReplyContent() {
  request({
    url: "/reply_content",
    method: "post",
    data: {
      group_id: groupId.value,
      item_name: replyTitle.value,
      content: replyContent.value,
    },
  }).then((res) => {
    replyContentDialog.value = false;
    replyContent.value = "";
    getReplys();
  });
}

//删除回复
function deleteReplyGroup(id) {
  request({
    url: "/reply?id=" + id,
    method: "delete",
  }).then((res) => {
    visible.value = false;
    getReplys();
  });
}

//删除回复
function deleteReplyContent(id) {
  request({
    url: "/reply_content?id=" + id,
    method: "delete",
  }).then((res) => {
    getReplys();
  });
}

//编辑回复
function editReplyContent(save, id, title, content) {
  if (save === "yes") {
    const data = {
      reply_id: replyId.value,
      reply_title: replyTitle.value,
      reply_content: replyContent.value,
    };
    request({
      url: "/reply_content_save",
      method: "post",
      data: data,
    }).then((res) => {
      editReplyContentDialog.value = false;
      getReplys();
    });
  } else {
    editReplyContentDialog.value = true;
    replyId.value = id;
    replyTitle.value = title;
    replyContent.value = content;
  }
}

//获取快捷回复
function getReplys() {
  request({
    url: "/replys",
    method: "get",
  }).then((res) => {
    console.log("getReplys", res);
    replys.value = res;
    visible.value = replys.value.map(() => false);
  });
}

//搜索回复
function searchReply() {
  replySearchListActive.value = [];
  if (replySearch.value === "") {
    replySearchList.value = [];
  }
  request({
    url: "/reply_search",
    method: "post",
    data: {search: replySearch.value},
  }).then((result) => {
    replySearchList.value = result;
    for (var i in result) {
      replySearchListActive.value.push(result[i].group_id);
    }
  });
}

//获取黑名单
function getIpblacks() {
  request({
    url: "/ipblack",
    method: "get",
  }).then((data) => {
    ipBlacks.value = data;
  });
}

//删除黑名单
function delIpblack(ip) {
  request({
    url: "/ipblack?ip=" + ip,
    method: "delete",
    data: {ip: ip},
  }).then((result) => {
    ElMessage.success("删除成功");
    //删除后重新获取
    getIpblacks()
  });
}

//划词搜索
function selectText() {
  const selection = window.getSelection();
  console.log("selecter", selection);
  console.log("selecter.rangeCount", selection.rangeCount);
  if (selection.rangeCount > 0) {
    const selectedText = selection.toString();
    console.log("selectedText", selectedText);
    if (selectedText.trim() !== "") {
      replySearch.value = selectedText.trim();
      console.log("自动触发搜索", selection);
      searchReply(); // 自动触发搜索
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  display: flex;
  overflow: hidden;
  width: 100%; /* 容器宽度设为100% */
}

.column {
  flex: 1; /* 使得三列宽度相等 */
  display: flex;
  flex-direction: column; /* 列内部为垂直方向 */
  //border: 1px solid #000; /* 分隔边框 */
  //padding: 10px;
}

.row {
  /* 默认情况下，行的高度将由其内容决定 */
  /* 但你可以为特定的行指定高度 */
  border-bottom: 1px solid #ccc; /* 除了最后一行外的分隔边框 */
  //padding: 10px;
  flex-grow: 1;
}

.flex-item-1 {
  flex: 1; /* 第一列占据更多的空间 */
}

.flex-item-2 {
  flex: 2; /* 第二列占据适中的空间 */
}
.kefuFaceBox {
  position: absolute;
  background: #fff;
  z-index: 999;
}

.faceBoxList {
  list-style: none;
  padding: 0;
  margin: 0;
}

.faceBoxList li {
  cursor: pointer;
  float: left;
  border: 1px solid #e8e8e8;
  width: 28px;
  overflow: hidden;
  margin: -1px 0 0 -1px;
  padding: 4px 2px;
  text-align: center;
}

.flex-item-3 {
  flex: 1; /* 第三列占据较少的空间 */
}

/*客服聊天主板*/
.chatBg {
  background: #fff;
  border: solid 1px #e6e6e6;
  //overflow: hidden;
}

.chatBg .el-tabs__header {
  margin: 0;
}

.clear {
  clear: both;
}

//.el-row{width:100%}
.chatLeft {
  //height: 100%;
  margin-left: 4px;
  overflow: auto;
}

.chatBgContext .el-row {
  margin-bottom: 5px;
}

.chatBgContext {
  position: relative;
  height: 98%;
  width: 100%;
}

.chatBox {
  //width: 100%;
  //height: 100%;
  overflow: auto;
  overflow-y: auto;
  //overflow-x: hidden;
}

* {
  padding: 0;
  margin: 0;
}

.clear {
  clear: both;
}

@-webkit-keyframes bounce-up {
  25% {
    -webkit-transform: translateY(10px);
  }
  50%,
  100% {
    -webkit-transform: translateY(0);
  }
  75% {
    -webkit-transform: translateY(-10px);
  }
}

@keyframes bounce-up {
  25% {
    transform: translateY(10px);
  }
  50%,
  100% {
    transform: translateY(0);
  }
  75% {
    transform: translateY(-10px);
  }
}

.el-aside {
  height: 100%;
  background: #fff;
}

.textDark {
  color: #343a40;
}

.bgInfo {
  background-color: #17a2b8;
}

.bgSuccess {
  background-color: #28a745;
}

.bgDanger {
  background-color: #dc3545;
}

.bgInfo {
  background-color: #17a2b8;
}

.smallBox {
  border-radius: 0.25rem;
  box-shadow: 0 0 1px rgba(0, 0, 0, 0.125),
  0 1px 3px rgba(0, 0, 0, 0.2);
  display: block;
  margin-bottom: 20px;
  position: relative;
  padding: 10px;
  color: #fff;
}

.settingMain h2 {
  margin-bottom: 20px;
}

.settingMain h3 {
  font-size: 24px;
  margin-bottom: 10px;
}

.chatRight {
  height: 100%;
  background: #fff;
  overflow-x: hidden;
}

.onlineUsers {
  padding: 5px 1px;
  font-size: 12px;
  border-bottom: solid 1px #f1f1f1;
  border-left: 4px solid #fff;
  display: flex;
  cursor: pointer;
}

.onlineUsers a {
  color: #333;
}

.onlineUsers:hover,
.onlineUsers.cur {
  background-color: rgb(238 247 255);
  border-left: 4px solid #4299e2;
}

.left-block {
  width: 50px;
}

.right-top {
  flex: 1; /* 右边上下两部分各自占据右边容器的一半高度（假设） */
  font-size: 12px;
}

.lastNewMsg {
  flex: 1; /* 右边上下两部分各自占据右边容器的一半高度（假设） */
  font-size: 12px;
  color: #7f7f7f;
  margin-top: 2px;
  overflow: hidden;
}

.right-container {
  flex: 1; /* 右边容器也占据剩余空间的一部分，这里假设为等宽 */
  display: flex; /* 右边容器内部也使用Flexbox */
  flex-direction: column; /* 垂直方向布局 */
}

.imgGray {
  -webkit-filter: grayscale(100%);
  -ms-filter: grayscale(100%);
  filter: grayscale(100%);
  filter: gray;
  color: #888;
}

.hasLastMsg {
  line-height: normal;
}

/*客服页*/
.chatKfPageApp {
  max-width: 800px;
  margin: 0 auto;
}

.chatCenter {
  background: #fff;
  max-width: 840px;
  margin: 0 auto;
  box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.3);
  border-top: none;
  overflow: hidden;
}

.chatContext {
  width: 100%;
  text-align: left;
  position: relative;
  background: rgb(245, 245, 245);
}

.chatBox {
  /*overflow-y: auto;*/
  overflow-x: hidden;
  background: rgb(245, 245, 245);
  /*margin-bottom: 80px;*/

  .chatRow {
    display: flex;
  }

  .chatRowMe {
    justify-content: end;

    .chatMsgContent {
      margin-right: 10px;
      position: relative;
      top: 10px;
    }
  }
}

.chatVisitorPage {
  height: calc(100% - 96px);
  overflow-y: auto;
}

.chatVisitorPage .chatBox {
  padding: 5px 4px;
}

.chatBox .el-col {
  margin: 10px 0;
}

.chatUser {
  font-size: 12px;
  white-space: nowrap;
  color: #999;
  text-align: left;
  margin: -5px 0px 3px 0px;
}

.chatMainPage {
  margin-top: 1px;
}

.chatContent {
  background-color: rgb(255, 255, 255);
  color: #000;
  border: 1px solid rgb(237, 237, 237);
  min-height: 20px;
  padding: 8px 15px;
  word-break: break-all;
  position: relative;
  border-radius: 5px;
  display: inline-block;
  line-height: 21px;
  font-size: 14px;
}

.chatContent2 {
  border-radius: 8px 8px 8px 0px;
  padding: 10px 15px;
}

.chatBoxMe {
  margin-top: 10px;
}

.chatBoxMe .chatContent2 {
  border-radius: 8px 8px 0px 8px;
  background-color: #cde0ff;
  color: #000;
}

.chatBoxMe .chatContent {
  float: right;
}

.chatBoxMe .chatContent:after {
  border-left-color: rgba(152, 225, 101, 1);
  border-right: none;
  left: auto;
  right: -5px;
}

.chatBoxMe .chatContent:before {
  border-left-color: rgb(152, 225, 101);
  border-right: none;
  right: -5px;
  left: auto;
}

.chatBoxMe .el-col-3 {
  float: right;
  text-align: right;
}

.chatBoxMe .chatUser {
  text-align: right;
}

.chatTitle {
  height: 30px;
  line-height: 30px;
  color: #1989fa;
}

.chatBoxSend {
  position: relative;
  padding-top: 5px;
  background: #fff;
  width: 100%;
  height: 90px;
  z-index: 99;
  border-top: 1px solid #e4e4e4;
}

.chatBoxSendBtn {
  float: right;
  margin: 12px 4px 0 0;
}

.footContact {
  text-align: center;
  position: absolute;
  bottom: 2px;
  left: 0;
  right: 0;
}

.footContact a {
  font-size: 12px;
  color: #999;
  text-decoration: none;
}

//.chatTime {
//  text-align: center;
//  color: #bbb;
//  margin: 5px 0;
//  font-size: 12px;
//}
.chatTime {
  text-align: center;
  color: #bbb;
  margin: 12px 0;
  font-size: 12px;
}

.chatTime span {
  display: inline-block;
  padding: 2px 5px;
  background: rgb(218, 218, 218);
  color: #fff;
}

.chatTimeHide {
  display: none;
}

.visitorInfo .el-menu-item {
  height: 40px;
  font-size: 12px;
}

.el-menu-item:hover,
.el-submenu__title:hover {
  background-color: #f1f1f1; /* 修改 hover 时的背景色 */
  color: #333; /* 修改 hover 时的文字颜色 */
}

.chatRightTitle {
  position: relative;
  color: #303133;
  height: 40px;
  line-height: 40px;
  padding: 0 10px;
  font-size: 14px;
  border-bottom: 1px solid #e4e7ed;
}

.chatRightTitle button {
  position: absolute; /* 绝对定位 */
  right: 0; /* 贴紧右侧 */
  top: 50%; /* 向上移动50%的自身高度 */
  transform: translateY(-50%); /* 向上移动自身高度的50%以实现完全居中 */
  text-decoration: none;
  color: #519eff;
}

.replyBox {
  font-size: 12px;
  //height: 100%;
  background: #fff;
  overflow-y: auto;
  width: 100%;
}

.replyItem:hover {
  background-color: #dadfd7;
  color: #67c23a;
}

.replyContent {
  padding: 0 10px;
}

.replySearch {
  margin: 5px 7px;
  width: 96% !important;
}

.iconBtnsBox {
  display: flex;
  align-items: center;
  color: #7e7e7e;
  height: 35px;
}

.iconBtnsBox .iconBtn {
  margin-right: 10px;
  cursor: pointer;
}

.kefuMainBg {
  background: #f5f5f5;
  border-right: solid 1px #e6e6e6;
  boder-top: none;
}

.kefuFuncBtns {
  background: #fff;
  margin: 2px 0px;
  color: #7f7f7f;
  border-bottom: 1px solid #e6e6e6;
  font-size: 12px;
  padding: 5px 0px;
}

.kefuFuncBox {
  //display: flex;
  //position: absolute;

  bottom: 0px;
  width: 100%;
  height: 100%;
  background: #fff;
  border-top: 1px solid #e5e5e5;
}

.kefuFolderBtn {
  vertical-align: middle;
}

.visitorReply {
  font-size: 14px;
  line-height: 24px;
}

.visitorReplyTitle {
}

.visitorReplyContent {
  color: #007aff;
  cursor: pointer;
}

.kefuSendBtn {
  position: relative;
  //right: 10px;
  bottom: 30px;
  z-index: 2;
}

.clear {
  clear: both;
}

.chatEntTitle {
  display: none;
  width: 100%;
  z-index: 9;
  margin: 0 auto;
  height: 56px;
  overflow: hidden;
  font-size: 16px;
  color: #fff;
  overflow: hidden;
  background-color: rgb(11 113 236);
  background-image: url(../images/visitor_title_bg.png);
  background-size: auto 72px;
  background-position: center 0;
  align-items: center;
}

.chatEntTitle span {
  margin-right: 10px;
}

.chatEntTitle .el-badge__content.is-fixed.is-dot {
  right: 17px;
  bottom: -5px;
  top: unset;
}

.chatEntBox {
  height: 100%;
  position: relative;
}

.chatArticle {
  display: none;
}

.visitorIconBox {
  display: flex;
  align-items: center;
  color: #9c9c9c;
}

.visitorIconBox .iconBtn {
  margin-right: 10px;
  cursor: pointer;
}

.productCard {
  cursor: pointer;
  padding: 5px;
  border-radius: 2px;
  width: auto;
  max-width: 730px;
  display: flex;
  border-radius: 5px;
}

.productCard img {
  width: 100px;
  height: 100px;
  margin-right: 15px;
}

.productCard .productCardPrice {
  color: #ff7736;
  font-weight: bold;
  font-size: 16px;
  margin-top: 10px;
}

.productCard .productCardTitle {
  color: #333;
}

@media screen and (min-width: 900px) {
  .chatCenter {
    max-height: 650px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    border-radius: 8px;
  }

  .chatVisitorPage {
    height: calc(100% - 156px);
  }

  .chatEntTitle {
    display: flex;
  }

  .chatEntTitleLogo {
    margin-left: 15px;
  }

  .visitorBody {
    display: flex;
    -ms-flex-pack: center;
    justify-content: center;
    -ms-flex-align: center;
    align-items: center;
  }

  .chatEntBox {
    width: calc(100% - 265px);
    float: left;
    border-right: 1px solid #e6e6e6;
  }

  .chatArticle {
    display: block;
    width: 260px;
    float: right;
    overflow-y: auto;
  }

  .hotQuestionTitle {
    padding: 10px 10px 10px 10px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.09);
    font-size: 16px;
    display: flex;
  }

  .hotQuestionTitle .fire {
    width: 20px;
    margin-right: 10px;
    color: rgb(250, 84, 28);
  }
}

.visitorEditorArea {
}

.visitorEditorArea textarea {
  padding: 7px 0 7px 8px;
  font-size: 16px;
  line-height: 21px;
  border: none;
}

.visitorEditorBtn {
  position: absolute;
  right: 10px;
  bottom: 2px;
}

.mainLeftMenu {
  width: 70px;
  float: left;
  height: 100%;
  text-align: center;
  background-color: #0a2f5a;
  position: relative;
}

.menuLeftItem {
  height: 55px;
  text-align: center;
  color: #fff;
  cursor: pointer;
  padding-top: 12px;
  width: 100%;
}

.menuLeftItem i,
.menuLeftItem .el-badge {
  display: block;
  margin-bottom: 2px;
  font-size: 20px;
}

.menuLeftItem span {
  font-size: 12px;
}

.menuLeftItemLogout {
  position: absolute;
  bottom: 0px;
}

.mainRight {
  width: calc(100% - 70px);
  height: 100%;
  float: left;
}

.mainIframe {
  width: 100%;
  height: 100%;
}

.menuLeftItem:active,
.menuLeftItem.active {
  background: #2b5a96;
}

.chatNotice {
  text-align: center;
  margin: 12px 0px;
}

.chatNoticeContent {
  display: inline-block;
  word-break: break-all;
  color: rgba(0, 0, 0, 0.45);
  margin: 0 24px;
  max-width: calc(100% - 48px);
  background-color: #fff;
  border-radius: 16px;
  font-size: 12px;
  padding: 4px 16px;
}

.chatRowAvator {
  margin-right: 10px;
  flex-shrink: 0;
}

.chatBoxMe .chatRowAvator {
  margin-left: 10px;
}

.allNotice {
  font-size: 12px;
  margin: 10px 0px;
  line-height: 23px;
  color: #666;
}

.chatArea .el-textarea__inner {
  border: none;
}

/* 定义滚动条的宽度、高度和背景色 */
::-webkit-scrollbar {
  width: 2px;
  height: 5px;
  background-color: #f5f5f5;
}

/* 定义滚动条滑块的样式 */
::-webkit-scrollbar-thumb {
  background-color: #c5c5c5;
}

/* 定义滚动条滑块在 hover 状态下的样式 */
::-webkit-scrollbar-thumb:hover {
  background-color: #999;
}
</style>
